﻿namespace Microsoft.EntityFrameworkCore;

public static class EntityFrameworkCoreExtensions
{
    public static async Task<int> AddIdentityRangeAsync<TEntity>(
        this DbContext context,
        IEnumerable<TEntity> entities,
        CancellationToken cancellationToken = default)
        where TEntity : class, new()
    {
        var table = context.Set<TEntity>().EntityType.ClrType.Name;

        await using var transcation = await context.Database.BeginTransactionAsync(cancellationToken);
        try
        {
            await context.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [{table}] ON", cancellationToken);

            await context.Set<TEntity>().AddRangeAsync(entities, cancellationToken);

            var result = await context.SaveChangesAsync(cancellationToken);

            await context.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT [{table}] OFF", cancellationToken);

            await transcation.CommitAsync(cancellationToken);

            return result;
        }
        catch (Exception)
        {
            await transcation.RollbackAsync(cancellationToken);

            return 0;
        }
    }
}